import * as dayjs from 'dayjs'
// dayjs常用的函数封装
 
export const TIME_FORMAT_ZHCN = 'YYYY年MM月DD HH时mm分ss秒'
export const TIME_FORMAT_ZHCN_NO_SECOND = 'YYYY年MM月DD HH时mm分'
export const TIME_FORMAT_ZHCN_NO_TIME = 'YYYY年MM月DD日'
export const TIME_FORMAT_ZHCN_NO_DATE = 'HH时mm分ss秒'

// 格式化时间
// 示例：formatTime('2021-01-01 00:00:00', 'YYYY-MM-DD HH:mm:ss')
export const formatTime = (time: string, format = 'YYYY-MM-DD HH:mm:ss') => {
    return dayjs(time).format(format)
}

// 计算两个时间的差，返回天/小时/分钟/秒，可选
// 示例：diffTime('2021-01-01 00:00:00', '2021-01-02 00:00:00', 'day')
export const diffTime = (time1: string, time2: string, type: 'day' | 'hour' | 'minute' | 'second' = 'day') => {
    const time = dayjs(time1).diff(dayjs(time2), type)
    return time
}

// 计算与当前时间的差，返回天/小时/分钟/秒，可选
// 示例：diffTime('2021-01-01 00:00:00', 'day')
export const diffTimeNow = (time: string, type: 'day' | 'hour' | 'minute' | 'second' = 'day') => {
    const timeNow = dayjs().diff(dayjs(time), type)
    return timeNow
}

// 按月分隔数组对象，相同月份的放在一起
// 示例：groupByMonth([{time: '2021-01-01 00:00:00', name: '张三'}, {time: '2021-01-02 00:00:00', name: '李四'}])
export const groupByMonth = (arr: any[]) => {
    const obj: any = {}
    arr.forEach(item => {
        const month = dayjs(item.time).format('YYYY-MM')
        if (!obj[month]) {
            obj[month] = []
        }
        obj[month].push(item)
    })
    return obj
}